package com.weixin.program.cron;

import com.weixin.program.config.WeixinProperties;
import com.weixin.program.delay.DelayQueueTask;
import com.weixin.program.task.Task;
import com.weixin.program.ro.UserData;
import com.weixin.program.utils.HolidayUtil;
import com.weixin.program.utils.HttpClientProxy;
import com.weixin.program.utils.TemplateUtil;
import com.weixin.program.utils.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年02⽉26⽇<br/>
 * @version：v1.0.0<br>
 */
@Slf4j
@Component
public class AlertCron {

    @Autowired
    WeixinProperties properties;

    /**
     * 每天8点55分执行一次
     */
    @Scheduled(cron = "0 55 08 * * ?")
    public void morning() throws Exception {
        log.info("定时任务发送提醒消息,当前日期:{}", LocalDate.now());
        List<String> holidays = HolidayUtil.HOLIDAYS;
        String nowDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        DayOfWeek today = LocalDate.now().getDayOfWeek();
        // 既不是节假日也不是周末--发送提醒消息
        if (!holidays.contains(nowDate) && today != DayOfWeek.SATURDAY && today != DayOfWeek.SUNDAY) {
            String token = WeixinUtil.getToken(properties.getAppid(), properties.getAppsecret());
            String touserid = properties.getTouserid();
            UserData userData = WeixinUtil.getUserData(touserid, token);
            String remindMsg = TemplateUtil.buildRemindMsg(properties.getTouserid(), userData.getNickName(), properties.getRemindtemplateid());
            log.info("发送提醒消息内容:{}", remindMsg);
            String sendUrl = properties.getTemplateurl() + token;
            String response = HttpClientProxy.post(sendUrl, remindMsg);
            log.info("发送提醒消息响应:{}", response);
            // 将消息放入延迟队列中,会有监听任务监听打卡的情况,放入2个任务，每个任务延迟时间为二分钟
            int delayTime = properties.getAlter();
            long milliLong = 0L;
            for (int i = 0; i < properties.getCount(); i++) {
                if (i == 0) {
                    milliLong = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                }
                String taskName = "定时提醒任务【" + (i + 1) + "】";
                Task task = new Task(taskName, properties.getTouserid(), milliLong, delayTime, TimeUnit.SECONDS);
                DelayQueueTask.getDelayQueue().add(task);
                milliLong = Task.getDelayTime(milliLong, delayTime, TimeUnit.SECONDS);
                String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                String effectTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(milliLong), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                log.info(taskName + "放入成功,当前时间:{}|生效时间:{}", currentTime, effectTime);
            }
        }
    }


    /**
     * 每天18点05执行一次
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 05 18 * * ?")
    public void afternoon() throws Exception {
        log.info("定时任务发送提醒消息,当前日期:{}", LocalDate.now());
        List<String> holidays = HolidayUtil.HOLIDAYS;
        String nowDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        DayOfWeek today = LocalDate.now().getDayOfWeek();
        // 既不是节假日也不是周末--发送提醒消息
        if (!holidays.contains(nowDate) && today != DayOfWeek.SATURDAY && today != DayOfWeek.SUNDAY) {
            String token = WeixinUtil.getToken(properties.getAppid(), properties.getAppsecret());
            String touserid = properties.getTouserid();
            UserData userData = WeixinUtil.getUserData(touserid, token);
            String remindMsg = TemplateUtil.buildRemindMsg(properties.getTouserid(), userData.getNickName(), properties.getRemindtemplateid());
            log.info("发送提醒消息内容:{}", remindMsg);
            String sendUrl = properties.getTemplateurl() + token;
            String response = HttpClientProxy.post(sendUrl, remindMsg);
            log.info("发送提醒消息响应:{}", response);
            // 将消息放入延迟队列中,会有监听任务监听打卡的情况,放入2个任务，每个任务延迟时间为二分钟
            int delayTime = properties.getAlter();
            long milliLong = 0L;
            for (int i = 0; i < properties.getCount(); i++) {
                if (i == 0) {
                    milliLong = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                }
                String taskName = "定时提醒任务【" + (i + 1) + "】";
                Task task = new Task(taskName, properties.getTouserid(), milliLong, delayTime, TimeUnit.SECONDS);
                DelayQueueTask.getDelayQueue().add(task);
                milliLong = Task.getDelayTime(milliLong, delayTime, TimeUnit.SECONDS);
                String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                String effectTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(milliLong), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                log.info(taskName + "放入成功,当前时间:{}|生效时间:{}", currentTime, effectTime);
            }
        }
    }

}
